<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
*/

class User_Plugin_Auth_AuthPlugin extends Zend_Controller_Plugin_Abstract
{
	
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
     // 	$facebook	 = $this->_setupFacebook();
		$loginUrl = array('login','auth','user');

		$allowed_actions  = array('login','logout','forgetpassword','resetpassword','signup','thanks','signupnext');
		$allowed_modules  = array('default');
  
        $auth = Zend_Auth::getInstance();
	    $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('Redirector');
     
		if ($request->getModuleName() != 'default' &&
				 !$auth->hasIdentity() && !in_array($request->getActionName(), $allowed_actions))
		{
            
			$redirector->gotoSimpleAndExit($loginUrl[0],$loginUrl[1],$loginUrl[2]);
        }
		else if($auth->hasIdentity() && $request->getActionName() == 'login')
		{
         	$r = new Zend_Controller_Action_Helper_Redirector;
			$r->gotoUrl('/user/dashboard')->redirectAndExist();
		}
        
		#ACL CHECK
                $acl= new User_Plugin_Auth_Acl();
		Zend_Registry::set('acl', $acl);
        
		$this->_aclCheck($auth, $request, $allowed_modules, $allowed_actions, $redirector);
    }


	private function _aclCheck($auth, $request, $allowed_modules, $allowed_actions, $redirector)
	{
		if ($auth->hasIdentity() && !in_array($request->getModuleName(), $allowed_modules)
								 && !in_array($request->getActionName(), $allowed_actions))
		{
            $resource = $request->getModuleName()."_".strtolower($request->getControllerName());
            $action = $request->getActionName();
           	$has_per = $this->hasPermission($resource, $action, true);
			
            if (!$has_per)
			{
              $this->getResponse()
					->setHttpResponseCode(403);

			  $request->setModuleName('default')
						->setControllerName('error')
						->setActionName('access')
						->setDispatched(true);
			}
        }
	}

	public function hasPermission($resource, $action, $applyToNavigation = false)
	{
        
		$auth		= Zend_Auth::getInstance();
        #if admin return true (Access throughout the application)
        
		if($auth->getIdentity()->role_id == User_Model_DbTable_Role::ADMIN_USER) return true;
		$acl = Zend_Registry::get('acl');
		
		if($applyToNavigation)
		{
			//assign acl to navigation
			Zend_Layout::getMvcInstance()
                   ->getView()
                   ->navigation()
                   ->setAcl($acl)
                   ->setRole($auth->getIdentity()->role);
		}

		return $acl->isAllowed($auth->getIdentity()->role,$resource, $action);
	}
}

?>